package com.victor9ac.mashup.elasticsearch.tasks;

import java.text.ParseException;
import java.util.List;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.springframework.stereotype.Component;

import com.victor9ac.mashup.api.Commentaries;
import com.victor9ac.mashup.api.MashupDataType;
import com.victor9ac.mashup.elasticsearch.converter.ElasticSearchCommentConverter;
import com.victor9ac.mashup.elasticsearch.converter.ElasticSearchConverter;
import com.victor9ac.mashup.elasticsearch.converter.ElasticSearchConverterFactory;
import com.victor9ac.mashup.elasticsearch.converter.ElasticSearchImagesConverter;
import com.victor9ac.mashup.es.ESReader;
import com.victor9ac.mashup.es.ESWriter;

public class ElasticSearchClient implements ElasticSearchOperation {

//	private static final String COMMENT_INDEX = "comment.index";

	ESWriter esWriter;
	ESReader esReader;


	public Object getFromMyPersistence(String keyword,
			MashupDataType mashupDataType) throws ParseException {

		SearchResponse searchResponse = esReader.read(keyword,
				mashupDataType.name());
		
		ElasticSearchConverter elasticSearchConverter = ElasticSearchConverterFactory.buildConverter(mashupDataType);

		return elasticSearchConverter.convert(searchResponse);
	}

	public void setFromMyPersistence(Object obj,
			MashupDataType mashupDataType ,String indexName) {
		try {
			
			ElasticSearchConverter elasticSearchConverter = ElasticSearchConverterFactory.buildConverter(obj);
			
			List<XContentBuilder> contentList = elasticSearchConverter.buildJson(obj);
			if (hasContentValid(contentList)){
				esWriter.writeBulk(contentList, mashupDataType, indexName);				
			}
			
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	private boolean hasContentValid(List<XContentBuilder> contentList) {
		return contentList != null && !contentList.isEmpty() && contentList.size()>0;
	}


	/*
	 * setters
	 */

	public void setEsWriter(ESWriter esWriter) {
		this.esWriter = esWriter;
	}

	public void setEsReader(ESReader esReader) {
		this.esReader = esReader;
	}

}
